<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
    <title>商品列表 - 助农购物网站</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="icon" type="image/x-icon" href="${pageContext.request.contextPath}/logo/favicon.ico">
    <link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <jsp:include page="../common/header.jsp"/>
    
    <div class="container mt-4">
        <div class="row mb-3">
            <div class="col-md-12">
                <form action="${pageContext.request.contextPath}/client/product?action=list" method="get" class="d-flex">
                    <input type="text" class="form-control me-2" name="keyword" placeholder="搜索商品..." value="${keyword}">
                    <button type="submit" class="btn btn-primary">搜索</button>
                </form>
            </div>
        </div>
        
        <c:if test="${error != null}">
            <div class="alert alert-danger">${error}</div>
        </c:if>
        
        <div class="row">
            <c:choose>
                <c:when test="${products != null && !empty products}">
                    <c:forEach var="product" items="${products}">
                        <div class="col-md-3 mb-4">
                            <div class="card h-100">
                                <c:if test="${product.imageUrl != null && !empty product.imageUrl}">
                                    <img src="${product.imageUrl}" class="card-img-top" alt="${product.productName}" style="height: 200px; object-fit: cover;">
                                </c:if>
                                <div class="card-body d-flex flex-column">
                                    <h5 class="card-title">${product.productName}</h5>
                                    <p class="card-text text-muted">${product.category}</p>
                                    <p class="card-text text-danger fs-4">¥${product.price}</p>
                                    <div class="mt-auto">
                                        <a href="${pageContext.request.contextPath}/client/product?action=detail&id=${product.productId}" class="btn btn-primary w-100 mb-2">查看详情</a>
                                        <c:if test="${sessionScope.user != null}">
                                            <button type="button" class="btn btn-success w-100" onclick="addToCart(${product.productId}, '${product.productName}', ${product.stock})">加入购物车</button>
                                        </c:if>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </c:forEach>
                </c:when>
                <c:otherwise>
                    <div class="col-md-12">
                        <div class="alert alert-info">
                            <h5>暂无商品</h5>
                            <p>商品列表为空，请稍后再试。</p>
                        </div>
                    </div>
                </c:otherwise>
            </c:choose>
        </div>
        
        <nav aria-label="Page navigation">
            <ul class="pagination justify-content-center">
                <li class="page-item ${page == 1 ? 'disabled' : ''}">
                    <a class="page-link" href="?page=${page-1}&keyword=${keyword}">上一页</a>
                </li>
                <li class="page-item">
                    <a class="page-link" href="?page=${page+1}&keyword=${keyword}">下一页</a>
                </li>
            </ul>
        </nav>
    </div>
    
    <script src="${pageContext.request.contextPath}/js/bootstrap.bundle.min.js"></script>
    <script>
        // 加入购物车
        function addToCart(productId, productName, stock) {
            if (stock <= 0) {
                alert('商品已售罄');
                return;
            }
            
            const quantity = 1; // 列表页默认数量为1
            
            const params = new URLSearchParams();
            params.append('productId', productId);
            params.append('quantity', quantity);
            
            fetch('${pageContext.request.contextPath}/client/cart?action=add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                body: params.toString()
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    alert('已添加到购物车');
                    // 更新购物车数量
                    updateCartCount();
                } else {
                    alert(data.message || '添加失败');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('添加失败，请重试');
            });
        }
        
        // 更新购物车数量
        function updateCartCount() {
            fetch('${pageContext.request.contextPath}/client/cart?action=count')
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        const cartCountEl = document.getElementById('cartCount');
                        if (cartCountEl) {
                            cartCountEl.textContent = data.count;
                            if (data.count > 0) {
                                cartCountEl.style.display = 'inline';
                            } else {
                                cartCountEl.style.display = 'none';
                            }
                        }
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
        }
    </script>
</body>
</html>

